<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta charset="UTF-8">
    <title>商城购物车界面</title>
    <link rel="stylesheet" type="text/css" href="css/public.css"/>
    <link rel="stylesheet" type="text/css" href="css/carts.css"/>
    <script src="js/jquery-3.6.0.js" type="text/javascript" charset="utf-8"></script>
    <script src="js/cart.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<%
    String user_id = (String) session.getAttribute("user_id");
    String username = (String) session.getAttribute("username");
    if (username != null) {
%>
<div class="head">
    <div class="shouye_head">
        <a href="first.jsp">商城首页</a>
    </div>
</div>

<div class="cart">
    <div class="cart-head">
        <div class="column g-select">
            <div class="g-checkbox">
                <input type="checkbox" class="all each">
            </div>
            全选
        </div>
        <div class="column g-images">图片</div>
        <div class="column g-goodsname">商品名称</div>
        <div class="column g-props">商品信息</div>
        <div class="column g-price">单价</div>
        <div class="column g-quantity">数量</div>
        <div class="column g-sum">小计</div>
        <div class="column g-action">操作</div>
    </div>
    <c:forEach items="${carList}" var="item">
        <div class="carts-goods">
            <div class="cell c-select">
                <div class="c-checkbox">
                    <input type="checkbox" class="each">
                </div>
            </div>
            <div class="cell c-images">
                <a href="./detail.do?id=${item.goods_id}" title="${item.goods_name}"><img src="${item.pic}" alt="${item.goods_name}"></a>
            </div>
            <div class="cell c-goodsname"><a href="#" title="${item.goods_name}">${item.goods_name}</a></div>
            <div class="cell c-props">${item.goods_name}</div>
            <div class="cell c-price">
                <span>￥</span>
                <div class="c-price_num">${item.unitprice}</div>
            </div>
            <div class="cell c-quantity">
                <button type="button" class="reduce" data-goods-id="${item.goods_id}" data-user-id="${user_id}">-</button>
                <input type="text"  value="${item.quantity}" class="text_num">
                <button type="button" class="add" data-goods-id="${item.goods_id}" data-user-id="${user_id}">+</button>
            </div>
            <div class="cell c-sum">
                <span>￥</span>
                <div class="c-sum_num">
                    <c:set var="totalPrice" value="${item.unitprice * item.quantity}" />
                        ${totalPrice}
                </div>
            </div>
            <div class="cell c-action">
                <a href="deletecar.do?id=${item.goods_id}" class="remove">移除商品</a>
            </div>
        </div>

    </c:forEach>
</div>
<div class="payment">
    <div class="cart-pay">
        <div class="pay-left">
            <div class="select_all">
                <input type="checkbox" class="all each">
                全选
            </div>
            <div class="goods_num">
                已选择数量:
                <span>0</span>
                件
            </div>
        </div>
        <div class="pay-right">
            <div class="right_jie">
                <div class="btn">
                    <a href="#" onclick="confirmPayment(); return false;">结算</a>
                </div>
                <div class="price-sum">
                    <div class="price-show">总价是：</div>
                    <div class="show-money">
                        ￥
                        <span>00.00</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    function confirmPayment() {
        // 支付成功后显示提示
        alert("结算成功！");
    }

    function updateQuantity(goodsId, userId, action,button) {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {

                var quantityInput = button.parentNode.querySelector(".text_num");
                var currentQuantity = parseInt(quantityInput.value);

                if (action === "add") {
                    quantityInput.value = currentQuantity + 1;
                } else if (action === "reduce" && currentQuantity > 1) {
                    quantityInput.value = currentQuantity - 1;
                }
                updateTotalPrice();
                updateTotalPriceAndQuantity();
            }
        };
        xhttp.open("GET", "./updateQuantity.do?goodsId=" + goodsId + "&userId=" + userId + "&action=" + action , true);
        xhttp.send();

    }
    // 如果有商品选择复选框，也要监听它们的变化
    document.querySelectorAll('.each').forEach(function(checkbox) {
        checkbox.addEventListener('change', function() {
            updateTotalPrice();
            updateTotalPriceAndQuantity();
        });
    });

    function updateTotalPriceAndQuantity() {
        console.log("1111");
        var totalPrice = 0;
        var totalQuantity = 0;

        document.querySelectorAll('.carts-goods').forEach(function(goods) {
            if (goods.querySelector('.each').checked) {
                var price = parseFloat(goods.querySelector('.c-price_num').textContent);
                var quantity = parseInt(goods.querySelector('.text_num').value);
                totalPrice += price * quantity;
                totalQuantity += quantity;
            }
        });

        document.querySelector('.show-money span').textContent = totalPrice.toFixed(2);
        document.querySelector('.goods_num span').textContent = totalQuantity;
    }

    document.querySelectorAll('.reduce, .add').forEach(function(button) {
        button.addEventListener('click', function(event) {
            var goodsId = this.getAttribute('data-goods-id');
            var userId = this.getAttribute('data-user-id');
            var action = this.classList.contains('add') ? 'add' : 'reduce';

            updateQuantity(goodsId, userId, action, this);

            event.stopPropagation();
        }, true);
    });

    function updateTotalPrice() {
        console.log("1111");
        var totalPrice = 0;
        document.querySelectorAll('.carts-goods').forEach(function(goods) {
            if (goods.querySelector('.each').checked) { // 确保商品被选中
                var price = parseFloat(goods.querySelector('.c-price_num').textContent);
                var quantity = parseInt(goods.querySelector('.text_num').value);
                totalPrice += price * quantity;
            }
        });
        document.querySelector('.show-money span').textContent = totalPrice.toFixed(2);
    }
</script>

</body>
<%
} else {
%>
<p>请先登录！</p>
<%
    }
%>
</html>
